<template>
	<div class="system-menu-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="800px">
			<el-form ref="menuDialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="100px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="上级菜单">
							<el-cascader :disabled="!state.ruleForm.parentMenuId && state.dialog.type == 'edit'"
								:options="state.menuData"
								:props="{ checkStrictly: true, emitPath: false, value: 'menuId', label: 'menuName' }"
								placeholder="请选择上级菜单" clearable class="w100" v-model="state.ruleForm.parentMenuId">
								<template #default="{ node, data }">
									<span>{{ data.menuName }}</span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="菜单类型">
							<el-radio-group v-model="state.ruleForm.menuType">
								<el-radio label="menu">菜单</el-radio>
								<!-- <el-radio label="btn">按钮</el-radio> -->
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单名称" prop="menuName">
							<el-input v-model="state.ruleForm.menuName" placeholder="菜单名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<template v-if="state.ruleForm.menuType === 'menu'">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="路由名称" prop="menuCode">
								<el-input v-model="state.ruleForm.menuCode" placeholder="路由中的 menuCode 值"
									clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="路由路径">
								<el-input v-model="state.ruleForm.menuUrl" placeholder="路由中的 path 值"
									clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="重定向">
								<el-input v-model="state.ruleForm.redirect" placeholder="请输入路由重定向" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜单图标">
								<IconSelector placeholder="请输入菜单图标" v-model="state.ruleForm.icon" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="组件路径">
								<el-input v-model="state.ruleForm.component" placeholder="组件路径" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="权限资源">
								<el-input @click.native="editItem()" v-model="state.ruleForm.functionResourceCode"
									placeholder="请输入权限资源" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="排序">
								<el-input v-model.number="state.ruleForm.seqNo" placeholder="排序（越小越前）"
									clearable></el-input>
							</el-form-item>
						</el-col>





					</template>
					<template v-if="state.ruleForm.menuType === 'menu'">

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="前端隐藏">
								<el-radio-group v-model="state.ruleForm.meta.isHide">
									<el-radio :label="true">隐藏</el-radio>
									<el-radio :label="false">显示</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="页面缓存">
								<el-radio-group v-model="state.ruleForm.meta.isKeepAlive">
									<el-radio :label="true">缓存</el-radio>
									<el-radio :label="false">不缓存</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否固定">
								<el-radio-group v-model="state.ruleForm.meta.isAffix">
									<el-radio :label="true">固定</el-radio>
									<el-radio :label="false">不固定</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="显示模式">
								<el-radio-group v-model.number="state.ruleForm.showType">
									<el-radio :label="0">有子菜单时显示</el-radio>
									<el-radio :label="1">有权限时显示</el-radio>
									<el-radio :label="2">总是显示</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						
					</template>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>

		<resourceSelector ref="resourceSelectorRef" @selectCode="selectCode"></resourceSelector>

	</div>
</template>

<script setup lang="ts" name="systemMenuDialog">
import { ElMessage } from 'element-plus';
import { defineAsyncComponent, reactive, ref, watch } from 'vue';






// 导入接口
import { useMenuApi } from "/@/api/menu";


const rules = {
	menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
	menuCode: [{ required: true, message: '请输入路由名称', trigger: 'blur' }]
}






// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/iconSelector/index.vue'));


const resourceSelector = defineAsyncComponent(() => import('./dialogResource.vue'));


// 定义变量内容
const menuDialogFormRef = ref();

const resourceSelectorRef = ref();




const state = reactive({
	// 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
	ruleForm: {
		menuType: 'menu', // 菜单类型
		parentMenuId: "", // 上级菜单ID
		menuName: "", // 菜单名称
		menuCode: "",// 菜单编码
		menuUrl: "", // path
		redirect: "",// 重定向
		icon: "", // 图标
		component: "",// 组件路径
		functionResourceCode: "",// 权限资源
		seqNo: "",
		showType: "",
		meta: {
			isKeepAlive: true, // 是否缓存
			isAffix: false, // 是否固定
			isHide: false // 是否前端隐藏
		}
	},
	menuId: "",
	menuData: [] as any, // 上级菜单数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});



const selectCode = (row: any) => {
	console.log(row)
	state.ruleForm.functionResourceCode = row.resourceFullPath;
}



// 打开弹窗
const openDialog = (type: string, row?: any) => {
	if (type === 'edit') {
		// 模拟数据，实际请走接口
		console.log(row)
		state.menuId = row.menuId;
		state.ruleForm.parentMenuId = row.parentMenuId || "";
		state.ruleForm.menuName = row.menuName || "";
		state.ruleForm.menuCode = row.menuCode || "";
		state.ruleForm.menuUrl = row.menuUrl || "";
		state.ruleForm.redirect = row.redirect || "";
		state.ruleForm.icon = row.icon || "";
		state.ruleForm.component = row.component || "";
		state.ruleForm.functionResourceCode = row.functionResourceCode || "";
		state.ruleForm.seqNo = row.seqNo;
		state.ruleForm.showType = row.showType;
		state.ruleForm.meta.isKeepAlive = row.meta.isKeepAlive;
		state.ruleForm.meta.isAffix = row.meta.isAffix;

		state.ruleForm.meta.isHide = row.meta.isHide;





		state.dialog.title = '修改菜单';
		state.dialog.submitTxt = '修 改';
	} else {
		state.menuId = "";
		state.dialog.title = '新增菜单';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用


		state.ruleForm.parentMenuId = "";
		state.ruleForm.menuName = "";
		state.ruleForm.menuCode = "";
		state.ruleForm.menuUrl = "";
		state.ruleForm.redirect = "";
		state.ruleForm.icon = "";
		state.ruleForm.component = "";
		state.ruleForm.functionResourceCode = "";
		state.ruleForm.seqNo = "";
		state.ruleForm.meta.isHide = false;
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};


const editItem = () => {
	resourceSelectorRef.value.openDialog();
}

// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {



	const metaData = {
		isKeepAlive: state.ruleForm.meta.isKeepAlive, // 是否缓存
		isAffix: state.ruleForm.meta.isAffix, // 是否固定
		icon: state.ruleForm.icon,
		isHide: state.ruleForm.meta.isHide,
		isIframe: false,
		isLink: "",
		redirect: state.ruleForm.redirect,
		roles: [],
		title: state.ruleForm.menuName
	}

	let params = {
		menuId: state.menuId,
		icon: state.ruleForm.icon,
		menuName: state.ruleForm.menuName,
		menuCode: state.ruleForm.menuCode,
		menuUrl: state.ruleForm.menuUrl,
		showType: state.ruleForm.showType,
		componentPath: state.ruleForm.component,
		functionResourceCode: state.ruleForm.functionResourceCode,
		seqNo: state.ruleForm.seqNo,
		metaData: JSON.stringify(metaData)
	} as any;

	if (state.ruleForm.parentMenuId) params["parentMenuId"] = state.ruleForm.parentMenuId;

	if (state.dialog.type === 'add') {
		params.menuId = "-1";
		params["type"] = "0";
		params["status"] = "1";

		insertMenu(params);

	} else {
		params.menuId = state.menuId;

		updateMenuById(params);

	}





	// closeDialog(); // 关闭弹窗
	// emit('refresh');
	// if (state.dialog.type === 'add') { }
	// setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
};



/**
 * 修改菜单的状态
 * @param menuId 
 * @param status 
 */
const updateMenuById = async (params: object) => {
	try {
		await useMenuApi().updateMenuById(params);
		ElMessage.success("操作成功");
		closeDialog(); // 关闭弹窗
		emit('refresh');
	} catch (error) {
		ElMessage.error("操作失败请稍后再试");
	}
}

const insertMenu = async (params: object) => {
	try {
		await useMenuApi().insertMenu(params);
		ElMessage.success("操作成功");
		closeDialog(); // 关闭弹窗
		emit('refresh');
	} catch (error) {
		ElMessage.error("操作失败请稍后再试");
	}
}













watch(
	() => state.dialog.isShowDialog,
	(newValue) => {
		if (newValue == true) {
			getMenusAdminAll();
		}
	}, { immediate: true }
);






const getMenusAdminAll = async () => {
	const params = {};
	let res = await useMenuApi().getMenusAdminAll(params);
	res = backEndInit(res);
	state.menuData = res;
}



/**
 * 初始化菜单
 * @param routes 
 */
const backEndInit = (routes: any) => {
	if (!routes) return;
	let routesTemp: any = []
	routes.map((item: any) => {
		item.path = item.menuUrl;
		item.name = item.menuCode;
		item.component = item.componentPath;
		if (item.metaData) {
			item.meta = JSON.parse(item.metaData);
			if (item.meta.redirect) {
				item.redirect = item.meta.redirect;
			}
		} else {
			item.meta = {
				isKeepAlive: true, // 是否缓存
				isAffix: false, // 是否固定
				icon: "",
				isHide: false,
				isIframe: false,
				isLink: "",
				redirect: "",
				roles: [],
				title: item.menuName
			}
		}
		routesTemp.push(item);
	});
	return routesTemp;
}






// 暴露变量
defineExpose({
	openDialog,
});
</script>
